<template>
  <div>
    <a-card :bordered="false">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="教职工">
                <a-input v-model="queryParams.staffName" placeholder="请输入教职工姓名" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="合同名称">
                <a-input v-model="queryParams.name" placeholder="请输入合同名称" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="合同开始时间">
                <a-date-picker
                  v-model="queryParams.contractStartDate"
                  placeholder="请选择合同开始时间"
                  allow-clear
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="合同结束时间">
                <a-date-picker
                  v-model="queryParams.contractEndDate"
                  placeholder="请选择合同结束时间"
                  allow-clear
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <div style="float: right;">
                <a-button type="primary" @click="handleQuery">
                  <a-icon type="search" />
                  查询
                </a-button>
                <a-button style="margin-left: 8px" @click="resetQuery">
                  <a-icon type="redo" />
                  重置
                </a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作 -->
      <div class="table-operations" style="margin-bottom: 16px;">
        <a-button type="primary" @click="$refs.createForm.handleAdd()" v-hasPermi="['system:contract:add']">
          <a-icon type="plus" />
          新增
        </a-button>
        <a-button type="primary" :disabled="single" @click="$refs.createForm.handleUpdate(undefined, ids)"
                  v-hasPermi="['system:contract:edit']">
          <a-icon type="edit" />
          修改
        </a-button>
        <a-button type="danger" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:contract:remove']">
          <a-icon type="delete" />
          删除
        </a-button>
        <a-button type="primary" @click="handleExport" v-hasPermi="['system:contract:export']">
          <a-icon type="download" />
          导出
        </a-button>
      </div>
      <!-- 增加修改 -->
      <create-form
        ref="createForm"
        :staffOptions="staffOptions"
        :statusOptions="dict.type['sys_normal_disable']"
        @ok="getList"
      />
      <!-- 数据展示 -->
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="contractList"
        :row-key="'contractId'"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <span slot="name" slot-scope="record"
              @click="previewPdf(record.filePath)"
              :style="{ color: 'blue', textDecoration: 'underline', cursor: 'pointer' }">
            {{ record.name }}
        </span>
        <a-tag slot="status" :color="convertColor(record)" slot-scope="record">
          {{ convertColor(record) === 'green' ? '正常' : convertColor(record) === 'orange' ? '即将过期' : '已过期' }}
        </a-tag>
        <div slot="action" slot-scope="record">
          <a @click="$refs.createForm.handleUpdate(record, undefined)" v-hasPermi="['system:contract:edit']">
            <a-icon type="edit" />
            续期
          </a>
          <a-divider type="vertical" v-hasPermi="['system:contract:remove']" />
          <a @click="handleDelete(record)" v-hasPermi="['system:contract:remove']">
            <a-icon type="delete" />
            删除
          </a>
          <a-divider type="vertical" v-if="convertColor(record)==='orange'||convertColor(record)==='red'"
                     v-hasPermi="['system:contract:remove']" />
          <a @click="handleOpen(record)" v-if="convertColor(record)==='orange'||convertColor(record)==='red'"
             v-hasPermi="['system:contract:remove']">
            <a-icon type="message" />
            发送通知
          </a>
        </div>

      </a-table>
      <a-modal v-model:visible="isModalVisible"
               width="1000px"
               @ok="closeModal"
               title="PDF 预览" @cancel="closeModal">
        <div class="scrollBox">
          <pdf v-for="item in numPages" :key="item" :src="pdfUrl" :page="item" ref="pdf"></pdf>
        </div>
      </a-modal>
      <!-- 分页 -->
      <a-pagination
        :current="queryParams.pageNum"
        :total="total"
        :page-size="queryParams.pageSize"
        show-size-changer
        show-quick-jumper
        @change="handlePaginationChange"
        @showSizeChange="handlePageSizeChange" />
    </a-card>
    <a-modal
      title="发送内容"
      :visible="msgModalVisible"
      @cancel="handleCancel"
    >
      <a-textarea
        v-model="msgContent"
        :maxLength="500"

        placeholder="请输入内容（最大500字符）"
        rows="8"
      />
      <template slot="footer">
        <a-button key="back" size='normal' @click="handleCancel">
          关闭
        </a-button>
        <a-button key="send" size='normal' type="primary" @click="handleSendMsg">
          发送
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { listContract, delContract, sendQyWxMsg,downloadContract } from '@/api/system/contract'
import CreateForm from './modules/CreateForm' // 引入CreateForm组件
import { staffTreeSelect } from '@/api/system/user'
import pdf from 'vue-pdf'

const columns = [

  {
    title: '合同Id',
    dataIndex: 'contractId',
    customRender: (text) => {
      return text ? text : '--'
    }
  },
  {
    title: '教职工姓名',
    dataIndex: 'staffName',
    customRender: (text) => {
      return text ? text : '--'
    }
  },
  {
    title: '合同名称',
    scopedSlots: {
      customRender: 'name'
    }
  }, {
    title: '合同开始时间',
    dataIndex: 'contractStartDate',
    customRender: (text) => {
      return text ? text : '--'
    }
  }, {
    title: '合同结束时间',
    dataIndex: 'contractEndDate',
    customRender: (text) => {

      return text ? text : '--'
    }
  },
  {
    title: '合同期限（天）',
    dataIndex: 'contractPeriod',
    customRender: (text, record) => {
      const start = new Date(record.contractStartDate)
      const end = new Date(record.contractEndDate)
      const timeDiff = end - start
      return Math.ceil(timeDiff / (1000 * 3600 * 24))

    }
  }
  , {
    title: '备注',
    dataIndex: 'remark',
    customRender: (text) => {
      return text ? text : '--'
    }
  }, {
    title: '状态',
    scopedSlots: {
      customRender: 'status'
    }
  },

  {
    title: '操作',
    scopedSlots: {
      customRender: 'action'
    }
  }
]
export default {
  name: 'Contract',
  components: {
    CreateForm, pdf
  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      record:null,
      msgContent: '',
      msgContent2: '',
      msgModalVisible: false,
      isModalVisible: false,
      pdfUrl: '',
      loading: false,
      contractList: [],
      staffOptions: [],
      total: 0,
      selectedRowKeys: [],
      selectedRows: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        staffId: null,
        staffName: null,
        name: null,
        contractStartDate: null,
        contractEndDate: null,
        contractPeriod: null,
        filePath: null
      },
      columns: columns,
      form: {},
      title: '',
      open: false,
      single: true,
      multiple: true,
      ids: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      numPages: 0

    }
  },
  created() {
    this.getList()
    this.getStaffTree()
  },
  methods: {
    handleSendMsg() {
      let that = this
      if (!this.msgContent) {
        this.$message.warning('消息内容不能为空')
        return
      }

      this.$confirm({
        title: '温馨提醒',
        content: '确认发送通知?',
        onOk: () => {
          let content = {
            touser: that.record.staffId,
            markdown: {
              content: that.msgContent2
            }
          }
          this.$message.loading({ content: '发送中...', key: 'syncDept', duration: 0 })
          console.log("content",content)
          return sendQyWxMsg(content)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success({ content: '发送成功！', key: 'syncDept' })
                setTimeout(() => {
                  that.msgModalVisible = false
                }, 400)

              } else {
                this.$message.error({ content: response.msg || '发送失败', key: 'syncDept' })
              }
            }).finally(() => {
              // 确保弹窗关闭
              this.$confirm().destroy()
            })
        },
        onCancel() {
        }
      })
    },
    handleCancel() {
      this.msgModalVisible = false
    },
    handleOpen(record) {
      this.msgModalVisible = true
      let color = this.convertColor(record)
      let msgContent = '';
      if (color === 'red') {
        msgContent = '尊敬的' + record.staffName + '\n' +
          '您好！我们在此提醒您，您的<font color="red">教师合同于' + record.contractEndDate + '到期</font>。\n' +
          '请您及时与人事部门联系，讨论合同续签事宜或其他相关事项。\n' +
          '感谢您在过去一段时间内对学校的贡献。\n' +
          '期待您的回复。祝好！';
      } else {
        msgContent = '尊敬的' + record.staffName + '\n' +
          '您好！我们在此提醒您，您的<font color="warning">教师合同将于' + record.contractEndDate + '到期</font>。\n' +
          '请您在此日期之前，及时与人事部门联系，讨论合同续签事宜或其他相关事项。\n' +
          '感谢您在过去一段时间内对学校的贡献。\n' +
          '期待您的回复。祝好！';
      }
      this.msgContent = msgContent
      this.msgContent2 = msgContent.replaceAll("<","####").replaceAll(">","@@@@")

      this.record = record
    },
    getNumPages(url) {
      let loadingTask = pdf.createLoadingTask(url)
      loadingTask.promise.then(pdf => {
        this.numPages = pdf.numPages
      }).catch(err => {
        console.error('pdf 加载失败', err)
      })
    },
    previewPdf(filePath) {
      downloadContract(filePath) // 调用下载功能
        .then(response => {
          console.log(response)
          // 创建一个 URL 对象
          const url = window.URL.createObjectURL(new Blob([response]));
          console.log(url)
          // 设置 pdfUrl
          this.pdfUrl = url;

          // 显示模态框
          this.isModalVisible = true;

          // 获取 PDF 页数
          this.getNumPages(url); // 使用生成的 URL 而不是原始 filePath
        })
        .catch(error => {
          console.error('下载文件失败:', error);
        });
    },
    closeModal() {
      this.isModalVisible = false // 关闭模态框
      this.pdfUrl = '' // 清空 PDF URL
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.contractId)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    convertColor(record) {
      const now = new Date()
      const end = new Date(record.contractEndDate)
      const timeDiff = end - now
      const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
      if (dayDiff > 30) {
        return 'green'
      } else if (dayDiff > 0 && dayDiff <= 30) {
        return 'orange'
      } else {
        return 'red'
      }
    },

    getStaffTree() {
      staffTreeSelect().then(response => {
        this.setDisableDeptNode(response.data[0])
        this.staffOptions = response.data
      })
    },
    setDisableDeptNode(treeNode) {
      // 调用递归搜索并传入输入值
      this.recursiveSearch(treeNode)
      return treeNode // 返回修改后的树
    },

    recursiveSearch(node) {
      let isSelectable = false // 用于标记是否有可选择的节点

      // 检查当前节点
      if (node.type === 'staff') {
        node.selectable = true
        isSelectable = true // 标记为可选择
      } else {
        node.selectable = false // 不可选择
      }
      // 如果有子节点，递归地检查每个子节点
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          // 递归调用并更新 isSelectable
          isSelectable = this.recursiveSearch(child) || isSelectable
        })
      }
      return isSelectable // 返回是否有可选择的节点
    },
    getList() {
      this.loading = true
      console.log(this.queryParams)
      listContract(this.queryParams).then((response) => {
        this.contractList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        ...this.queryParams,
        staffId: null,
        name: null,
        staffName: null,
        contractStartDate: null,
        contractEndDate: null,
        contractPeriod: null,
        filePath: null
      }
      this.handleQuery()
    },
    handlePaginationChange(page, pageSize) {
      this.queryParams.pageNum = page
      this.queryParams.pageSize = pageSize
      this.getList()
    },
    handlePageSizeChange(current, pageSize) {
      this.queryParams.pageSize = pageSize
      this.getList()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为' + contractIds + '的数据',
        onOk: () => {
          return delContract(contractIds)
            .then(() => {
              // console.log('删除成功')
              this.onSelectChange([], [])
              this.getList()
              this.$message.success(
                '删除成功',
                3
              )
            }).finally(() => {
              // 确保弹窗关闭
              this.$confirm().destroy()
            })
        },
        onCancel() {
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk() {
          that.download('system/contract/export', {
            ...that.queryParam
          }, `contract_${new Date().getTime()}.xlsx`)
        },
        onCancel() {
        }
      })
    }
  }
}
</script>
<style scoped>
.scrollBox {
  max-height: 600px; /* 设置最大高度 */
  overflow-y: auto; /* 允许垂直滚动 */
}

.pdf-page {
  margin: 10px 0; /* 添加页面之间的间距 */
}
</style>
